package edu.msg.jthr.backend.service.beans;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import edu.msg.jthr.backend.model.User;
import edu.msg.jthr.backend.repository.RepositoryException;
import edu.msg.jthr.backend.repository.UserRepository;
import edu.msg.jthr.backend.service.ServiceException;
import edu.msg.jthr.backend.service.UserService;
import edu.msg.jthr.backend.service.utils.PasswordService;

@Stateless
public class UserBean implements UserService {

	// private static final Logger LOG =
	// LoggerFactory.getLogger(UserBean.class);

	@EJB
	private UserRepository userDAO;

	public UserBean() {
	}

	@Override
	public void insert(User obj) throws ServiceException {
		try {
			String pass = encryptPassword(obj.getUserPass());
			obj.setUserPass(pass);
			userDAO.insert(obj);
			// LOG.info("Insertion succeded");
		} catch (RepositoryException e) {
			// LOG.error("Insertion failed - service", e);
			throw new ServiceException();
		}
	}

	@Override
	public User update(User obj) throws ServiceException {
		try {
			String pass = encryptPassword(obj.getUserPass());
			obj.setUserPass(pass);
			User temp = userDAO.update(obj);
			// LOG.info("Update succeded");
			return temp;
		} catch (RepositoryException e) {
			// LOG.error("Update failed - service", e);
			throw new ServiceException("Update failed - service", e);
		}
	}

	@Override
	public void delete(User obj) throws ServiceException {
		try {
			userDAO.delete(obj);
			// LOG.info("Delete succeded");
		} catch (RepositoryException e) {
			// LOG.error("Delete failed - service", e);
			throw new ServiceException("Delete failed - service", e);
		}
	}

	@Override
	public List<User> getAll() throws ServiceException {
		try {
			List<User> temp = userDAO.getAll();
			// LOG.info("getAll succeded");
			return temp;
		} catch (RepositoryException e) {
			// LOG.error("getAll failed - service", e);
			throw new ServiceException("getAll failed - service", e);
		}
	}

	@Override
	public User getById(Integer id) throws ServiceException {
		try {
			User temp = userDAO.getById(id);
			// LOG.info("getById succeded");
			return temp;
		} catch (RepositoryException e) {
			// LOG.error("getById failed - service", e);
			throw new ServiceException("getById failed - service", e);
		}
	}

	@Override
	public User getByName(String name) throws ServiceException {
		try {
			User temp = userDAO.getByName(name);
			// LOG.info("getByName succeded");
			return temp;
		} catch (RepositoryException e) {
			// LOG.error("getByName failed - service", e);
			throw new ServiceException("getByName failed - service", e);
		}
	}

	@Override
	public String encryptPassword(String pass) throws ServiceException {
		try {
			return PasswordService.generateHashedPassword(pass);
		} catch (Exception e) {
			throw new ServiceException("encryption failed - service", e);
		}
	}

}
